﻿using System;
using System.Collections.Generic;
using System.Net.Mail;
using System.Xml;

namespace Domain.Mail
{
    public class MailParser
    {
        private MailMessage mailMessage;
        private IDictionary<string, string> subjectTags;
        private IDictionary<string, string> bodyTags;

        public MailParser(string templateUri)
        {
            mailMessage = new MailMessage();
            subjectTags = new Dictionary<string, string>();
            bodyTags = new Dictionary<string, string>();

            XmlDocument doc = new XmlDocument();
            doc.Load(templateUri);

            mailMessage.Subject = doc.SelectSingleNode("//mail//subject").InnerText;
            mailMessage.Body = doc.SelectSingleNode("//mail//body").InnerText;
            mailMessage.IsBodyHtml = Convert.ToBoolean(doc.SelectSingleNode("//mail//body").Attributes["isHtml"].InnerText);
        }

        public MailParser(string subject, string body, bool isBodyHtml)
        {
            mailMessage = new MailMessage();
            mailMessage.Subject = subject;
            mailMessage.Body = body;
            mailMessage.IsBodyHtml = isBodyHtml;
        }

        public void AddSubjectTag(string tag, string value)
        {
            subjectTags.Add("{" + tag + "}", value);
        }

        public void AddBodyTag(string tag, string value)
        {
            bodyTags.Add("{" + tag + "}", value);
        }

        public MailMessage Parse()
        {
            foreach (KeyValuePair<string, string> i in subjectTags)
            {
                mailMessage.Subject = mailMessage.Subject.Replace(i.Key, i.Value);
            }

            foreach (KeyValuePair<string, string> i in bodyTags)
            {
                mailMessage.Body = mailMessage.Body.Replace(i.Key, i.Value);
            }

            return mailMessage;
        }
    }
}
